// pages/city/index.ts
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from "~/stores/app"
import type { roadLineState } from '~/../typings/types/line/add'

import type { itemState, cityInfoState } from '~/../typings/types/city'
import { back } from '~/utils/util'
import * as watch from '~/utils/watch'
let cityList: itemState[] = []
interface showState {
  label: string
  check: boolean
  children: itemState[]
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    title: '选择目的地' as string,
    checked: [] as itemState[],
    descCheck: [] as itemState[],
    showList: [] as showState[],
    isAllCheck: false,
    cityInfo: {
      doArea: [],
      doSiteList: []
    } as cityInfoState
  },
  handCurrenClick(e: any) {
    const idx = e.target.dataset.idx
    const { checked } = this.data
    checked.splice(idx + 1, checked.length - idx + 1)
    this.setData({
      checked
    })
    this.getShowList()
    this.allCheckChange()
  },
  allCheckChange() {
    if (this.data.checked.length > 1) {
      this.setData({
        isAllCheck: true
      })
    } else {
      this.setData({
        isAllCheck: false
      })
    }
  },
  getArr(arr: itemState[], children: itemState[], index = 0, newArr = [] as itemState[]): itemState[] {
    const checkInfo = arr[index]
    const info = children.find(el => el.label === checkInfo.label)
    if (info) {
      const newInfo = JSON.parse(JSON.stringify(info))
      delete newInfo.children
      newArr.push(newInfo)
      if (info.children && info.children.length > 0 && index < arr.length - 1) {
        return this.getArr(arr, info.children, index + 1, newArr)
      }
    }
    return newArr
  },
  handSubmit() {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('chooseEvent', [{
      destProvince: this.data.checked[0].label,
      destCity: this.data.checked[1].label,
      destArea: ''
    }] as roadLineState[]);
    back()
  },
  handOver() {
    if (this.data.descCheck.length == 0) {
      wx.showToast({
        icon: 'none',
        title: '请至少选择一个目的地'
      })
      return
    }
    const arr = [] as roadLineState[]
    this.data.descCheck.forEach(el => {
      arr.push({
        destProvince: this.data.checked[0].label,
        destCity: this.data.checked[1].label,
        destArea: el.label
      })
    })
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('chooseEvent', arr);
    back()
  },
  handActive(e: any) {
    const { descCheck, showList } = this.data
    const labelIndex = showList.findIndex(el => el.label === e.target.dataset.idx)
    const labelInfo = showList.find(el => el.label === e.target.dataset.idx)
    if (!labelInfo) return
    const info = labelInfo.children[e.target.dataset.n]
    if (info.children && info.children.length > 0) {
      const arr = this.data.checked
      arr.push(info)
      this.setData({
        checked: arr,
        descCheck: []
      })
      this.getShowList()
    } else {
      if (info.check) {
        labelInfo.children[e.target.dataset.n].check = false
        showList[labelIndex] = labelInfo
        const descIndex = descCheck.findIndex(el => el.label == info.label)
        descCheck.splice(descIndex, 1)
        this.setData({
          descCheck,
          showList
        })
      } else {
        labelInfo.children[e.target.dataset.n].check = true
        showList[labelIndex] = labelInfo
        descCheck.push(info)
        this.setData({
          descCheck,
          showList
        })
      }
      // const eventChannel = this.getOpenerEventChannel()
      // const arr = this.getArr([...this.data.checked, info], cityList)
      // eventChannel.emit('chooseEvent', arr);
      // back()
    }
    this.allCheckChange()
  },
  getShowList() {
    let arr: itemState[] = cityList
    if (this.data.checked.length > 0) {
      this.data.checked.forEach(el => {
        const info: itemState | undefined = arr.find((item: itemState) => item.label === el.label)
        if (info && info?.children) {
          arr = info.children
        }
      })
    }
    let newArr: showState[] = []
    arr.forEach(el => {
      const index = newArr.findIndex(item => item.label === el.pinYin)
      if (index >= 0) {
        const info = newArr[index]
        if (info && info?.children) {
          info.children.push(el)
        }
      } else {
        newArr.push({
          label: el.pinYin,
          check: false,
          children: [el]
        })
      }
    })
    this.setData({
      showList: newArr.sort((a, b) => (a.label > b.label) ? 1 : -1)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(this: any, e: any) {
    this.storeBinding = createStoreBindings(this, {
      store,
      fields: {
        cityName: 'getCityName',
        cityInfo: 'cityInfo',
      },
    });
    watch.setWatcher(this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(this: any) {
    this.storeBinding.destroyStoreBindings();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  watch: {
    cityInfo: function (e: cityInfoState) {
      if (e.doArea.length > 0) {
        const data = e.doArea
        cityList = data
        this.getShowList()
      }
    }
  }
})